from datetime import datetime
from app.models.mysql_db import db

class Device(db.Model):
    """设备模型"""
    __tablename__ = 'devices'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(64), unique=True, nullable=False)
    name = db.Column(db.String(100))
    status = db.Column(db.String(20))
    signature_secret = db.Column(db.String(128), nullable=False)
    created_at = db.Column(db.DateTime)
    last_online = db.Column(db.DateTime)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 新增设备状态字段
    battery_level = db.Column(db.Float, default=100.0)  # 电池电量百分比
    work_mode = db.Column(db.String(20), default='自动')  # 工作模式
    device_health = db.Column(db.Float, default=100.0)  # 设备健康状态百分比
    last_active = db.Column(db.DateTime)  # 上次活动时间
    
    def __init__(self, device_id, name=None, status='active', signature_secret=None):
        self.device_id = device_id
        self.name = name or f"Device_{device_id}"
        self.status = status
        self.signature_secret = signature_secret or 'device-secret-key'
        self.created_at = datetime.utcnow()
        self.last_online = datetime.utcnow()
        self.updated_at = datetime.utcnow()
        self.battery_level = 100.0
        self.work_mode = '自动'
        self.device_health = 100.0
        self.last_active = datetime.utcnow()
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'device_id': self.device_id,
            'name': self.name or f"Device_{self.device_id}",
            'status': self.status,
            'signature_secret': self.signature_secret,
            'last_online': self.last_online.isoformat() if self.last_online else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }